import { getEdit, setFile, updateEdit } from '@/store/actions/Profile'
import { Button, List, DatePicker, NavBar, Popup, Toast, Dialog } from 'antd-mobile'
import classNames from 'classnames'

import useInitialState from '@/hooks/useInitialState'
import styles from './index.module.scss'
import { useRef, useState } from 'react'
import EditInput from './EditInput'
import { useDispatch } from 'react-redux'
import EditList from './EditList'
import { formatedate } from '@/utils'
import { Logout } from '@/store/actions/login'
import { useHistory } from 'react-router-dom'
const Item = List.Item

const ProfileEdit = () => {
    const { userProfile } = useInitialState(getEdit, 'Profile')
    const dispatch =useDispatch()
    const history = useHistory()
    const [showBrith,setBrith] = useState(false)
    const fileRef=useRef<HTMLInputElement>(null)
    type InputState = {
        visible: boolean
        type: '' | 'name' | 'intro'
    }
    type ListState = {
        visible: boolean
        type: '' | 'photo' | 'gender'
    }
    const [showInput, setShowInput] = useState<InputState>({
        type: '',
        visible: false
    })
    const closehandle=()=>{
        setShowInput({type:'',visible:false})
    }
    const [showList, setShowList] = useState<ListState>({
        type: '',
        visible: false
    })
    const closeList=()=>{
        setShowList({type:'',visible:false})
    }
    const update=async(key:string,value:string)=>{
    if(key === 'photo'){
       return fileRef.current?.click()
    }
    await dispatch(updateEdit(key,value))
    Toast.show({
        icon: 'success',
        content: '修改成功'
      })
      closehandle()
      closeList()
    }
     const changeFile=async(e:React.ChangeEvent<HTMLInputElement>)=>{
        const file = e.target.files![0]
        if(!file)return
        const Newphoto = new FormData()
        Newphoto.append('photo',file)
       await dispatch(setFile(Newphoto))
       closeList()
     }
     const onBirthdayHide=()=>{ //日期取消事件
        setBrith(false)
     }
     const onUpdateBirthday=(value:Date)=>{//日期点击事件
    //  console.log(value,'eeeee');
     const newBirthday = formatedate(value) //单独封装的方法
    //  console.log(newBirthday);
    update('birthday',newBirthday)
    onBirthdayHide()
     }
     const onLogout = () => { //退出登录
        const handler = Dialog.show({
          title: '温馨提示',
          content: '亲，你确定退出吗？',
          closeOnAction: true,
          actions: [
            [
              {
                key: 'cancel',
                text: '取消',
                onClick: () => {
                  handler.close()
                }
              },
              {
                key: 'confirm',
                text: '退出',
                style: {
                  color: 'var(--adm-color-weak)'
                },
                onClick:()=>{
                    dispatch(Logout())
                    history.replace('/login')
                    Toast.show({
                        icon: 'success',
                        content: '退出成功'
                      })
                }
              }
            ]
          ]
        })
      }
    return (
        <div className={styles.root}>
            <div className="content">
                {/* 标题 */}
                <NavBar
                onBack={() => history.go(-1)}
                    style={{
                        '--border-bottom': '1px solid #F0F0F0'
                    }}
                >
                    个人信息
                </NavBar>
                <div className="wrapper">
                    {/* 列表 */}
                    <List className="profile-list">
                        {/* 列表项 */}
                        <Item
                            extra={
                                <span className="avatar-wrapper">
                                    <img
                                        width={24}
                                        height={24}
                                        src={userProfile.photo}
                                        alt=""
                                    />
                                </span>
                            }
                            arrow
                            onClick={() => setShowList({ visible: true, type: 'photo' })}
                        >
                            头像
                        </Item>
                        <Item arrow extra={userProfile.name}
                            onClick={() => setShowInput({ visible: true, type: 'name' })}
                        >
                            昵称
                        </Item>
                        <Item
                            arrow
                            extra={
                                <span className={classNames('intro', 'normal')}>
                                    {userProfile.intro||'未填写'}
                                </span>
                            }
                            onClick={() => setShowInput({ visible: true, type: 'intro' })}
                        >
                            简介
                        </Item>
                    </List>

                    <List className="profile-list">
                        <Item arrow extra={userProfile.gender ? '女':'男'} onClick={() => setShowList({ visible: true, type: 'gender' })}>
                            性别
                        </Item>
                        <Item arrow extra={userProfile.birthday}
                        onClick={()=>setBrith(true)}
                        >
                            生日
                        </Item>
                    </List>

                    <DatePicker
                        visible={showBrith}
                        value={new Date(userProfile.birthday)}   //当前选中的值
                        title="选择年月日"
                        onCancel={onBirthdayHide}             // 取消事件
                        onConfirm={onUpdateBirthday}          //点击确认
                        min={new Date('1980-01-01')}
                        max={new Date()}
                    />
                    <Popup visible={showInput.visible} position="right" destroyOnClose>
                        <EditInput closehandle={closehandle}  type={showInput.type} update={update} />
                    </Popup>
                    <Popup onMaskClick={closeList} visible={showList.visible} position='bottom' destroyOnClose>
                        <EditList  closeList={closeList} type={showList.type} update={update}/>
                    </Popup>
                    <input type="file" hidden ref={fileRef} onChange={changeFile} />
                </div>

                <div className="logout">
                    <Button className="btn" onClick={onLogout}>退出登录</Button>
                </div>
            </div>
        </div>
    )
}

export default ProfileEdit